#include "outputpreviewwidget.h"
#include <QPainter>
#include <QScrollBar>
#include <QApplication>
OutputPreviewWidget::OutputPreviewWidget(QWidget *parent)
    : QWidget(parent)
    , m_showingCover(true)
    , m_zoomFactor(0.5)
    , m_enableMargins(true)
{
    setupUI();
}
void OutputPreviewWidget::setupUI()
{
    m_layout = new QVBoxLayout(this);
    // 控制按钮
    m_controlLayout = new QHBoxLayout();
    m_showCoverButton = new QPushButton(tr("封面预览"));
    m_showContentButton = new QPushButton(tr("内容预览"));
    m_showCoverButton->setCheckable(true);
    m_showContentButton->setCheckable(true);
    m_showCoverButton->setChecked(true);
    connect(m_showCoverButton, &QPushButton::clicked, this, &OutputPreviewWidget::showCoverPreview);
    connect(m_showContentButton, &QPushButton::clicked, this, &OutputPreviewWidget::showContentPreview);
    m_zoomLabel = new QLabel(tr("缩放:"));
    m_zoomCombo = new QComboBox();
    m_zoomCombo->addItems({"25%", "50%", "75%", "100%", "125%", "150%"});
    m_zoomCombo->setCurrentText("50%");
    connect(m_zoomCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int index) {
        QStringList zooms = {"0.25", "0.5", "0.75", "1.0", "1.25", "1.5"};
        if (index >= 0 && index < zooms.size()) {
            m_zoomFactor = zooms[index].toDouble();
            if (m_previewPage) {
                m_previewPage->setZoomFactor(m_zoomFactor);
            }
        }
    });
    // 启用边距调整勾选
    m_enableMarginsCheck = new QCheckBox(tr("启用边距调整"));
    m_enableMarginsCheck->setChecked(true);
    connect(m_enableMarginsCheck, &QCheckBox::toggled, this, [this](bool on){
        m_enableMargins = on;
        if (m_previewPage) m_previewPage->setMarginsEnabled(on);
    });
    m_controlLayout->addWidget(m_showCoverButton);
    m_controlLayout->addWidget(m_showContentButton);
    m_controlLayout->addStretch();
    m_controlLayout->addWidget(m_zoomLabel);
    m_controlLayout->addWidget(m_zoomCombo);
    m_controlLayout->addSpacing(12);
    m_controlLayout->addWidget(m_enableMarginsCheck);
    // 预览区域
    m_scrollArea = new QScrollArea();
    m_previewPage = new PreviewPageWidget();
    m_previewPage->setZoomFactor(m_zoomFactor);
    m_previewPage->setMarginsEnabled(m_enableMargins);
    m_scrollArea->setWidget(m_previewPage);
    m_scrollArea->setWidgetResizable(true);
    m_layout->addLayout(m_controlLayout);
    m_layout->addWidget(m_scrollArea, 1);
}
void OutputPreviewWidget::setSettings(const OutputSettings& settings)
{
    m_settings = settings;
    if (m_previewPage) {
        m_previewPage->setSettings(settings);
    }
}
void OutputPreviewWidget::setSamplePages(const QList<QImage>& pages)
{
    m_samplePages = pages;
    updatePreview();
}
void OutputPreviewWidget::setCurrentFileFirstPage(const QImage& firstPage)
{
    m_currentFileFirstPage = firstPage;
    if (m_previewPage) {
        m_previewPage->setCurrentFileFirstPage(firstPage);
    }
    updatePreview();
}
void OutputPreviewWidget::showCoverPreview()
{
    m_showingCover = true;
    m_showCoverButton->setChecked(true);
    m_showContentButton->setChecked(false);
    updatePreview();
}
void OutputPreviewWidget::showContentPreview()
{
    m_showingCover = false;
    m_showCoverButton->setChecked(false);
    m_showContentButton->setChecked(true);
    updatePreview();
}
void OutputPreviewWidget::updatePreview()
{
    if (m_previewPage) {
        m_previewPage->setShowCover(m_showingCover);
        if (!m_showingCover && !m_samplePages.isEmpty()) {
            m_previewPage->setSampleImage(m_samplePages.first());
        }
        m_previewPage->update();
    }
}
// PreviewPageWidget 实现
PreviewPageWidget::PreviewPageWidget(QWidget *parent)
    : QWidget(parent)
    , m_showCover(true)
    , m_zoomFactor(0.5)
    , m_marginsEnabled(true)
    , m_dragging(false)
    , m_draggedElement(-1)
    , m_titleOffset(0, -50)
    , m_subtitleOffset(0, -20)
    , m_authorOffset(-100, 20)
    , m_dateOffset(100, 20)
{
    setBackgroundRole(QPalette::Base);
    setAutoFillBackground(true);
    setMouseTracking(true); // 启用鼠标跟踪
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
}
void PreviewPageWidget::setSettings(const OutputSettings& settings)
{
    m_settings = settings;
    update();
}
void PreviewPageWidget::setSampleImage(const QImage& image)
{
    m_sampleImage = image;
    update();
}
void PreviewPageWidget::setShowCover(bool showCover)
{
    m_showCover = showCover;
    update();
}
void PreviewPageWidget::setZoomFactor(double zoom)
{
    m_zoomFactor = zoom;
    updateGeometry();
    update();
}
void PreviewPageWidget::setMarginsEnabled(bool enabled)
{
    m_marginsEnabled = enabled;
    update();
}
void PreviewPageWidget::setCurrentFileFirstPage(const QImage& firstPage)
{
    m_currentFileFirstPage = firstPage;
    update();
}
void PreviewPageWidget::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton && m_showCover) {
        QPoint mousePos = event->pos();
        QSize pageSize(static_cast<int>(mmToPixels(A4_WIDTH_MM)), static_cast<int>(mmToPixels(A4_HEIGHT_MM)));
        QRect pageRect((width() - pageSize.width()) / 2, 10, pageSize.width(), pageSize.height());
        QPoint pageCenter = pageRect.center();
        // 检查点击的是哪个元素
        QRect titleRect = QRect(pageCenter + m_titleOffset - QPoint(50, 10), QSize(100, 20));
        QRect subtitleRect = QRect(pageCenter + m_subtitleOffset - QPoint(50, 10), QSize(100, 20));
        QRect authorRect = QRect(pageCenter + m_authorOffset - QPoint(50, 10), QSize(100, 20));
        QRect dateRect = QRect(pageCenter + m_dateOffset - QPoint(50, 10), QSize(100, 20));
        if (titleRect.contains(mousePos)) {
            m_dragging = true;
            m_draggedElement = 0;
            m_dragStartPos = mousePos;
            m_dragOffset = m_titleOffset;
        } else if (subtitleRect.contains(mousePos)) {
            m_dragging = true;
            m_draggedElement = 1;
            m_dragStartPos = mousePos;
            m_dragOffset = m_subtitleOffset;
        } else if (authorRect.contains(mousePos)) {
            m_dragging = true;
            m_draggedElement = 2;
            m_dragStartPos = mousePos;
            m_dragOffset = m_authorOffset;
        } else if (dateRect.contains(mousePos)) {
            m_dragging = true;
            m_draggedElement = 3;
            m_dragStartPos = mousePos;
            m_dragOffset = m_dateOffset;
        }
    }
}
void PreviewPageWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (m_dragging && m_draggedElement >= 0) {
        QPoint delta = event->pos() - m_dragStartPos;
        QPoint newOffset = m_dragOffset + delta;
        // 更新对应元素的位置
        switch (m_draggedElement) {
            case 0: m_titleOffset = newOffset; break;
            case 1: m_subtitleOffset = newOffset; break;
            case 2: m_authorOffset = newOffset; break;
            case 3: m_dateOffset = newOffset; break;
        }
        update();
    }
}
void PreviewPageWidget::mouseReleaseEvent(QMouseEvent *event)
{
    Q_UNUSED(event)
    m_dragging = false;
    m_draggedElement = -1;
}
void PreviewPageWidget::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    // 尺寸变化时重新计算并更新显示
    update();
}
void PreviewPageWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event)
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    // 创建真实A4画布
    QImage realA4Canvas = createRealA4Canvas();
    if (realA4Canvas.isNull()) {
        // 如果无法创建真实画布，使用原来的方法
        QSize availableSize = size();
        QSize pageSize = calculateOptimalPageSize(availableSize);
        QRect pageRect((width() - pageSize.width()) / 2, 10, 
                       pageSize.width(), pageSize.height());
        painter.fillRect(pageRect, Qt::white);
        painter.setPen(QPen(Qt::gray, 1));
        painter.drawRect(pageRect);
        if (m_showCover) {
            drawCoverPage(painter, pageRect);
        } else {
            drawContentPage(painter, pageRect);
        }
        return;
    }
    // 在真实A4画布上渲染内容
    renderToRealA4Canvas(realA4Canvas, m_showCover);
    // 计算缩放比例以适应预览窗口
    QSize availableSize = size();
    QSize scaledSize = realA4Canvas.size().scaled(availableSize.width() - 20, availableSize.height() - 20, 
                                                  Qt::KeepAspectRatio);
    // 居中绘制缩放后的A4画布
    QRect drawRect((width() - scaledSize.width()) / 2, 10, scaledSize.width(), scaledSize.height());
    // 绘制页面背景（白色）
    painter.fillRect(drawRect, Qt::white);
    // 绘制页面边框
    painter.setPen(QPen(Qt::gray, 1));
    painter.drawRect(drawRect);
    // 绘制缩放后的真实A4画布
    painter.drawImage(drawRect, realA4Canvas);
}
QSize PreviewPageWidget::calculateOptimalPageSize(const QSize& availableSize) const
{
    // A4纸的宽高比 (210:297)
    const double a4Ratio = A4_WIDTH_MM / A4_HEIGHT_MM; // 210/297 ≈ 0.707
    // 预留边距 - 使用相对边距而不是固定像素
    const int margin = qMax(10, availableSize.width() / 20); // 动态边距，最小10像素
    QSize usableSize = availableSize - QSize(margin * 2, margin * 2);
    if (usableSize.width() <= 0 || usableSize.height() <= 0) {
    return QSize(100, 141); // 最小尺寸，保持A4比例
}
    // 根据可用空间计算最佳尺寸
    int maxWidth = usableSize.width();
    int maxHeight = usableSize.height();
    // 计算基于宽度的最大高度
    int heightFromWidth = static_cast<int>(maxWidth / a4Ratio);
    // 计算基于高度的最大宽度
    int widthFromHeight = static_cast<int>(maxHeight * a4Ratio);
    QSize pageSize;
    if (heightFromWidth <= maxHeight) {
        // 宽度限制，高度自适应
        pageSize = QSize(maxWidth, heightFromWidth);
    } else {
        // 高度限制，宽度自适应
        pageSize = QSize(widthFromHeight, maxHeight);
    }
    // 确保最小尺寸
    pageSize.setWidth(qMax(pageSize.width(), 50));
    pageSize.setHeight(qMax(pageSize.height(), 71)); // 保持A4比例
    return pageSize;
}
QSize PreviewPageWidget::sizeHint() const
{
    // 使用动态计算而不是固定尺寸
    QSize availableSize(300, 400); // 默认可用空间
    return calculateOptimalPageSize(availableSize) + QSize(40, 40);
}
int PreviewPageWidget::heightForWidth(int w) const
{
    // 使用动态计算
    QSize availableSize(w, 1000); // 假设有足够的高度
    QSize pageSize = calculateOptimalPageSize(availableSize);
    return pageSize.height() + 40; // 加上边距
}
void PreviewPageWidget::drawCoverPage(QPainter& painter, const QRect& pageRect)
{
    if (!m_settings.coverPage.enabled) {
        // 如果封面页未启用，显示提示
        painter.setPen(Qt::gray);
        painter.setFont(QFont("Arial", 12));
        painter.drawText(pageRect, Qt::AlignCenter, tr("封面页未启用"));
        return;
    }
    // 计算页面边距，确保内容不会超出页面
    const int pageMargin = 20;
    QRect contentArea = pageRect.adjusted(pageMargin, pageMargin, -pageMargin, -pageMargin);
    // 绘制标题（真实渲染效果）
    if (!m_settings.coverPage.title.isEmpty()) {
        painter.save();
        painter.setFont(m_settings.coverPage.titleFont);
        painter.setPen(Qt::black);
        QPoint titlePos = contentArea.center() + m_titleOffset;
        // 计算文字的实际边界，支持自动换行
        QFontMetrics fm(m_settings.coverPage.titleFont);
        QString title = m_settings.coverPage.title;
        // 计算可用宽度，确保不超出页面边界
        int maxWidth = qMin(contentArea.width() - qAbs(m_titleOffset.x()) * 2, 
                           contentArea.width() - 40);
        maxWidth = qMax(maxWidth, 100); // 最小宽度
        // 自动换行处理
        QStringList lines;
        if (fm.horizontalAdvance(title) <= maxWidth) {
            lines << title;
        } else {
            // 需要换行
            QStringList words = title.split(' ');
            QString currentLine;
            for (const QString& word : words) {
                QString testLine = currentLine.isEmpty() ? word : currentLine + " " + word;
                if (fm.horizontalAdvance(testLine) <= maxWidth) {
                    currentLine = testLine;
                } else {
                    if (!currentLine.isEmpty()) {
                        lines << currentLine;
                        currentLine = word;
                    } else {
                        lines << word; // 单个词太长，强制换行
                    }
                }
            }
            if (!currentLine.isEmpty()) {
                lines << currentLine;
            }
        }
        // 绘制多行文字
        int lineHeight = fm.lineSpacing();
        int totalHeight = lines.size() * lineHeight;
        int startY = titlePos.y() - totalHeight / 2;
        for (int i = 0; i < lines.size(); ++i) {
            QRect lineRect(titlePos.x() - maxWidth/2, startY + i * lineHeight, 
                          maxWidth, lineHeight);
            painter.drawText(lineRect, Qt::AlignCenter, lines[i]);
        }
        // 绘制拖动提示框
        if (m_dragging && m_draggedElement == 0) {
            painter.setPen(QPen(Qt::blue, 2, Qt::DashLine));
            QRect dragRect(titlePos.x() - maxWidth/2, startY, maxWidth, totalHeight);
            painter.drawRect(dragRect);
        }
        painter.restore();
    }
    // 绘制副标题（真实渲染效果）
    if (!m_settings.coverPage.subtitle.isEmpty()) {
        painter.save();
        painter.setFont(m_settings.coverPage.subtitleFont);
        painter.setPen(Qt::black);
        QPoint subtitlePos = contentArea.center() + m_subtitleOffset;
        QFontMetrics fm(m_settings.coverPage.subtitleFont);
        QString subtitle = m_settings.coverPage.subtitle;
        int maxWidth = qMin(contentArea.width() - qAbs(m_subtitleOffset.x()) * 2, 
                           contentArea.width() - 40);
        maxWidth = qMax(maxWidth, 100);
        QStringList lines;
        if (fm.horizontalAdvance(subtitle) <= maxWidth) {
            lines << subtitle;
        } else {
            QStringList words = subtitle.split(' ');
            QString currentLine;
            for (const QString& word : words) {
                QString testLine = currentLine.isEmpty() ? word : currentLine + " " + word;
                if (fm.horizontalAdvance(testLine) <= maxWidth) {
                    currentLine = testLine;
                } else {
                    if (!currentLine.isEmpty()) {
                        lines << currentLine;
                        currentLine = word;
                    } else {
                        lines << word;
                    }
                }
            }
            if (!currentLine.isEmpty()) {
                lines << currentLine;
            }
        }
        int lineHeight = fm.lineSpacing();
        int totalHeight = lines.size() * lineHeight;
        int startY = subtitlePos.y() - totalHeight / 2;
        for (int i = 0; i < lines.size(); ++i) {
            QRect lineRect(subtitlePos.x() - maxWidth/2, startY + i * lineHeight, 
                          maxWidth, lineHeight);
            painter.drawText(lineRect, Qt::AlignCenter, lines[i]);
        }
        if (m_dragging && m_draggedElement == 1) {
            painter.setPen(QPen(Qt::blue, 2, Qt::DashLine));
            QRect dragRect(subtitlePos.x() - maxWidth/2, startY, maxWidth, totalHeight);
            painter.drawRect(dragRect);
        }
        painter.restore();
    }
    // 绘制作者（真实渲染效果）
    if (!m_settings.coverPage.author.isEmpty()) {
        painter.save();
        painter.setFont(m_settings.coverPage.authorFont);
        painter.setPen(Qt::black);
        QPoint authorPos = contentArea.center() + m_authorOffset;
        QFontMetrics fm(m_settings.coverPage.authorFont);
        QString author = m_settings.coverPage.author;
        int maxWidth = qMin(contentArea.width() - qAbs(m_authorOffset.x()) * 2, 
                           contentArea.width() - 40);
        maxWidth = qMax(maxWidth, 100);
        QStringList lines;
        if (fm.horizontalAdvance(author) <= maxWidth) {
            lines << author;
        } else {
            QStringList words = author.split(' ');
            QString currentLine;
            for (const QString& word : words) {
                QString testLine = currentLine.isEmpty() ? word : currentLine + " " + word;
                if (fm.horizontalAdvance(testLine) <= maxWidth) {
                    currentLine = testLine;
                } else {
                    if (!currentLine.isEmpty()) {
                        lines << currentLine;
                        currentLine = word;
                    } else {
                        lines << word;
                    }
                }
            }
            if (!currentLine.isEmpty()) {
                lines << currentLine;
            }
        }
        int lineHeight = fm.lineSpacing();
        int totalHeight = lines.size() * lineHeight;
        int startY = authorPos.y() - totalHeight / 2;
        for (int i = 0; i < lines.size(); ++i) {
            QRect lineRect(authorPos.x() - maxWidth/2, startY + i * lineHeight, 
                          maxWidth, lineHeight);
            painter.drawText(lineRect, Qt::AlignCenter, lines[i]);
        }
        if (m_dragging && m_draggedElement == 2) {
            painter.setPen(QPen(Qt::blue, 2, Qt::DashLine));
            QRect dragRect(authorPos.x() - maxWidth/2, startY, maxWidth, totalHeight);
            painter.drawRect(dragRect);
        }
        painter.restore();
    }
    // 绘制日期（真实渲染效果）
    if (!m_settings.coverPage.date.isEmpty()) {
        painter.save();
        painter.setFont(m_settings.coverPage.dateFont);
        painter.setPen(Qt::black);
        QPoint datePos = contentArea.center() + m_dateOffset;
        QFontMetrics fm(m_settings.coverPage.dateFont);
        QString date = m_settings.coverPage.date;
        int maxWidth = qMin(contentArea.width() - qAbs(m_dateOffset.x()) * 2, 
                           contentArea.width() - 40);
        maxWidth = qMax(maxWidth, 100);
        QStringList lines;
        if (fm.horizontalAdvance(date) <= maxWidth) {
            lines << date;
        } else {
            QStringList words = date.split(' ');
            QString currentLine;
            for (const QString& word : words) {
                QString testLine = currentLine.isEmpty() ? word : currentLine + " " + word;
                if (fm.horizontalAdvance(testLine) <= maxWidth) {
                    currentLine = testLine;
                } else {
                    if (!currentLine.isEmpty()) {
                        lines << currentLine;
                        currentLine = word;
                    } else {
                        lines << word;
                    }
                }
            }
            if (!currentLine.isEmpty()) {
                lines << currentLine;
            }
        }
        int lineHeight = fm.lineSpacing();
        int totalHeight = lines.size() * lineHeight;
        int startY = datePos.y() - totalHeight / 2;
        for (int i = 0; i < lines.size(); ++i) {
            QRect lineRect(datePos.x() - maxWidth/2, startY + i * lineHeight, 
                          maxWidth, lineHeight);
            painter.drawText(lineRect, Qt::AlignCenter, lines[i]);
        }
        if (m_dragging && m_draggedElement == 3) {
            painter.setPen(QPen(Qt::blue, 2, Qt::DashLine));
            QRect dragRect(datePos.x() - maxWidth/2, startY, maxWidth, totalHeight);
            painter.drawRect(dragRect);
        }
        painter.restore();
    }
}
void PreviewPageWidget::drawContentPage(QPainter& painter, const QRect& pageRect)
{
    QRect contentRect = getContentRect(pageRect);
    // 优先显示当前文件的第一页
    if (!m_currentFileFirstPage.isNull()) {
        // 缩放当前文件第一页以适应内容区域
        QImage scaledImage = m_currentFileFirstPage.scaled(contentRect.size(), 
                                                           Qt::KeepAspectRatio, 
                                                           Qt::SmoothTransformation);
        // 居中绘制图片
        QPoint imagePos = contentRect.center() - QPoint(scaledImage.width()/2, scaledImage.height()/2);
        painter.drawImage(imagePos, scaledImage);
    } else if (!m_sampleImage.isNull()) {
        // 如果没有当前文件第一页，使用示例图片
        QImage scaledImage = m_sampleImage.scaled(contentRect.size(), 
                                                 Qt::KeepAspectRatio, 
                                                 Qt::SmoothTransformation);
        // 居中绘制图片
        QPoint imagePos = contentRect.center() - QPoint(scaledImage.width()/2, scaledImage.height()/2);
        painter.drawImage(imagePos, scaledImage);
    } else {
        // 如果都没有，显示灰色占位符
        painter.fillRect(contentRect, QColor(240, 240, 240));
        painter.setPen(Qt::gray);
        painter.setFont(QFont("Arial", 12));
        painter.drawText(contentRect, Qt::AlignCenter, tr("无内容预览"));
    }
}
void PreviewPageWidget::drawHeaderFooter(QPainter& painter, const QRect& pageRect)
{
    // 绘制页眉（真实渲染效果）
    if (m_settings.header.enabled && (m_showCover ? m_settings.header.showOnCoverPage : true)) {
        painter.save();
        painter.setFont(m_settings.header.font);
        painter.setPen(m_settings.header.color);
        // 计算页眉区域，考虑边距
        int headerTop = pageRect.top() + static_cast<int>(mmToPixels(5)); // 页眉距离顶部5mm
        int headerHeight = static_cast<int>(mmToPixels(10)); // 页眉高度10mm
        int headerLeft = pageRect.left() + static_cast<int>(mmToPixels(m_settings.margins.left));
        int headerWidth = pageRect.width() - static_cast<int>(mmToPixels(m_settings.margins.left + m_settings.margins.right));
        QRect headerRect(headerLeft, headerTop, headerWidth, headerHeight);
        // 计算对齐方式
        Qt::Alignment headerAlign = Qt::AlignVCenter;
        switch (m_settings.header.position) {
            case HeaderFooterPosition::Left:
                headerAlign |= Qt::AlignLeft;
                break;
            case HeaderFooterPosition::Center:
                headerAlign |= Qt::AlignHCenter;
                break;
            case HeaderFooterPosition::Right:
                headerAlign |= Qt::AlignRight;
                break;
        }
        // 替换变量，实现真实的变量替换
        QString headerText = m_settings.header.text;
        headerText.replace("{title}", m_settings.coverPage.title);
        headerText.replace("{date}", m_settings.coverPage.date);
        headerText.replace("{page}", "1");
        headerText.replace("{totalPages}", "10");
        // 支持多行页眉，使用真实的字体渲染
        QFontMetrics fm(m_settings.header.font);
        QStringList lines = headerText.split('\n');
        int lineHeight = fm.lineSpacing();
        int totalHeight = lines.size() * lineHeight;
        int startY = headerRect.top() + (headerRect.height() - totalHeight) / 2;
        for (int i = 0; i < lines.size(); ++i) {
            QRect lineRect(headerRect.left(), startY + i * lineHeight, 
                          headerRect.width(), lineHeight);
            painter.drawText(lineRect, headerAlign, lines[i]);
        }
        painter.restore();
    }
    // 绘制页脚（真实渲染效果）
    if (m_settings.footer.enabled && (m_showCover ? m_settings.footer.showOnCoverPage : true)) {
        painter.save();
        painter.setFont(m_settings.footer.font);
        painter.setPen(m_settings.footer.color);
        // 计算页脚区域，考虑边距
        int footerBottom = pageRect.bottom() - static_cast<int>(mmToPixels(5)); // 页脚距离底部5mm
        int footerHeight = static_cast<int>(mmToPixels(10)); // 页脚高度10mm
        int footerLeft = pageRect.left() + static_cast<int>(mmToPixels(m_settings.margins.left));
        int footerWidth = pageRect.width() - static_cast<int>(mmToPixels(m_settings.margins.left + m_settings.margins.right));
        QRect footerRect(footerLeft, footerBottom - footerHeight, footerWidth, footerHeight);
        // 计算对齐方式
        Qt::Alignment footerAlign = Qt::AlignVCenter;
        switch (m_settings.footer.position) {
            case HeaderFooterPosition::Left:
                footerAlign |= Qt::AlignLeft;
                break;
            case HeaderFooterPosition::Center:
                footerAlign |= Qt::AlignHCenter;
                break;
            case HeaderFooterPosition::Right:
                footerAlign |= Qt::AlignRight;
                break;
        }
        // 替换变量，实现真实的变量替换
        QString footerText = m_settings.footer.text;
        footerText.replace("{title}", m_settings.coverPage.title);
        footerText.replace("{date}", m_settings.coverPage.date);
        footerText.replace("{page}", "1");
        footerText.replace("{totalPages}", "10");
        // 支持多行页脚，使用真实的字体渲染
        QFontMetrics fm(m_settings.footer.font);
        QStringList lines = footerText.split('\n');
        int lineHeight = fm.lineSpacing();
        int totalHeight = lines.size() * lineHeight;
        int startY = footerRect.top() + (footerRect.height() - totalHeight) / 2;
        for (int i = 0; i < lines.size(); ++i) {
            QRect lineRect(footerRect.left(), startY + i * lineHeight, 
                          footerRect.width(), lineHeight);
            painter.drawText(lineRect, footerAlign, lines[i]);
        }
        painter.restore();
    }
}
QRect PreviewPageWidget::getContentRect(const QRect& pageRect) const
{
    int leftMargin = static_cast<int>(mmToPixels(m_settings.margins.left));
    int rightMargin = static_cast<int>(mmToPixels(m_settings.margins.right));
    int topMargin = static_cast<int>(mmToPixels(m_settings.margins.top));
    int bottomMargin = static_cast<int>(mmToPixels(m_settings.margins.bottom));
    // 考虑页眉页脚占用的空间
    if (m_settings.header.enabled && (m_showCover ? m_settings.header.showOnCoverPage : true)) {
        topMargin = qMax(topMargin, static_cast<int>(mmToPixels(20))); // 页眉需要额外空间
    }
    if (m_settings.footer.enabled && (m_showCover ? m_settings.footer.showOnCoverPage : true)) {
        bottomMargin = qMax(bottomMargin, static_cast<int>(mmToPixels(20))); // 页脚需要额外空间
    }
    return QRect(pageRect.left() + leftMargin,
                pageRect.top() + topMargin,
                pageRect.width() - leftMargin - rightMargin,
                pageRect.height() - topMargin - bottomMargin);
}
double PreviewPageWidget::mmToPixels(double mm) const
{
    // 假设显示DPI为96，实际应该从QApplication::primaryScreen()->logicalDotsPerInch()获取
    const double DPI = 96.0;
    const double MM_PER_INCH = 25.4;
    return (mm / MM_PER_INCH * DPI) * m_zoomFactor;
}
// 旧的对比引导已删除，改为在主绘制中直接以淡灰色覆盖目标区域
QImage PreviewPageWidget::createRealA4Canvas() const
{
    QSize realA4Size = calculateRealA4Size();
    if (realA4Size.width() <= 0 || realA4Size.height() <= 0) {
        return QImage();
    }
    QImage canvas(realA4Size, QImage::Format_ARGB32_Premultiplied);
    canvas.fill(Qt::white);
    return canvas;
}
QSize PreviewPageWidget::calculateRealA4Size() const
{
    // A4纸尺寸：210mm × 297mm
    // 使用300 DPI (每英寸300像素) 作为标准打印分辨率
    const double dpi = 300.0;
    const double mmToInch = 25.4; // 1英寸 = 25.4毫米
    int widthPixels = static_cast<int>((A4_WIDTH_MM / mmToInch) * dpi);
    int heightPixels = static_cast<int>((A4_HEIGHT_MM / mmToInch) * dpi);
    return QSize(widthPixels, heightPixels);
}
void PreviewPageWidget::renderToRealA4Canvas(QImage& canvas, bool isCover) const
{
    if (canvas.isNull()) return;
    QPainter painter(&canvas);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setRenderHint(QPainter::TextAntialiasing);
    QRect canvasRect(0, 0, canvas.width(), canvas.height());
    if (isCover) {
        // 渲染封面页
        renderCoverPageToCanvas(painter, canvasRect);
    } else {
        // 渲染内容页
        renderContentPageToCanvas(painter, canvasRect);
    }
    // 渲染页眉页脚
    if ((m_settings.header.enabled && (isCover ? m_settings.header.showOnCoverPage : true)) ||
        (m_settings.footer.enabled && (isCover ? m_settings.footer.showOnCoverPage : true))) {
        renderHeaderFooterToCanvas(painter, canvasRect);
    }
}
void PreviewPageWidget::renderCoverPageToCanvas(QPainter& painter, const QRect& canvasRect) const
{
    if (!m_settings.coverPage.enabled) {
        // 如果封面页未启用，显示提示
        painter.setPen(Qt::gray);
        QFont font("Arial", 12);
        painter.setFont(font);
        painter.drawText(canvasRect, Qt::AlignCenter, tr("封面页未启用"));
        return;
    }
    // 计算页面边距（按真实毫米转换为像素）
    const double dpi = 300.0;
    const double mmToInch = 25.4;
    const double mmToPixels = dpi / mmToInch;
    int pageMargin = static_cast<int>(20 * mmToPixels); // 20mm边距
    QRect contentArea = canvasRect.adjusted(pageMargin, pageMargin, -pageMargin, -pageMargin);
    // 渲染标题（真实字体大小）
    if (!m_settings.coverPage.title.isEmpty()) {
        painter.save();
        painter.setFont(m_settings.coverPage.titleFont);
        painter.setPen(Qt::black);
        QPoint titlePos = contentArea.center() + m_titleOffset;
        // 计算文字的实际边界，支持自动换行
        QFontMetrics fm(m_settings.coverPage.titleFont);
        QString title = m_settings.coverPage.title;
        // 计算可用宽度
        int maxWidth = contentArea.width() - qAbs(m_titleOffset.x()) * 2;
        maxWidth = qMax(maxWidth, static_cast<int>(50 * mmToPixels)); // 最小50mm宽度
        // 自动换行处理
        QStringList lines;
        if (fm.horizontalAdvance(title) <= maxWidth) {
            lines << title;
        } else {
            QStringList words = title.split(' ');
            QString currentLine;
            for (const QString& word : words) {
                QString testLine = currentLine.isEmpty() ? word : currentLine + " " + word;
                if (fm.horizontalAdvance(testLine) <= maxWidth) {
                    currentLine = testLine;
                } else {
                    if (!currentLine.isEmpty()) {
                        lines << currentLine;
                        currentLine = word;
                    } else {
                        lines << word; // 单个词太长，强制换行
                    }
                }
            }
            if (!currentLine.isEmpty()) {
                lines << currentLine;
            }
        }
        // 绘制多行文字
        int lineHeight = fm.lineSpacing();
        int totalHeight = lines.size() * lineHeight;
        int startY = titlePos.y() - totalHeight / 2;
        for (int i = 0; i < lines.size(); ++i) {
            QRect lineRect(titlePos.x() - maxWidth/2, startY + i * lineHeight, 
                          maxWidth, lineHeight);
            painter.drawText(lineRect, Qt::AlignCenter, lines[i]);
        }
        painter.restore();
    }
    // 渲染副标题（真实字体大小）
    if (!m_settings.coverPage.subtitle.isEmpty()) {
        painter.save();
        painter.setFont(m_settings.coverPage.subtitleFont);
        painter.setPen(Qt::black);
        QPoint subtitlePos = contentArea.center() + m_subtitleOffset;
        QFontMetrics fm(m_settings.coverPage.subtitleFont);
        QString subtitle = m_settings.coverPage.subtitle;
        int maxWidth = contentArea.width() - qAbs(m_subtitleOffset.x()) * 2;
        maxWidth = qMax(maxWidth, static_cast<int>(50 * mmToPixels));
        QStringList lines;
        if (fm.horizontalAdvance(subtitle) <= maxWidth) {
            lines << subtitle;
        } else {
            QStringList words = subtitle.split(' ');
            QString currentLine;
            for (const QString& word : words) {
                QString testLine = currentLine.isEmpty() ? word : currentLine + " " + word;
                if (fm.horizontalAdvance(testLine) <= maxWidth) {
                    currentLine = testLine;
                } else {
                    if (!currentLine.isEmpty()) {
                        lines << currentLine;
                        currentLine = word;
                    } else {
                        lines << word;
                    }
                }
            }
            if (!currentLine.isEmpty()) {
                lines << currentLine;
            }
        }
        int lineHeight = fm.lineSpacing();
        int totalHeight = lines.size() * lineHeight;
        int startY = subtitlePos.y() - totalHeight / 2;
        for (int i = 0; i < lines.size(); ++i) {
            QRect lineRect(subtitlePos.x() - maxWidth/2, startY + i * lineHeight, 
                          maxWidth, lineHeight);
            painter.drawText(lineRect, Qt::AlignCenter, lines[i]);
        }
        painter.restore();
    }
    // 渲染作者（真实字体大小）
    if (!m_settings.coverPage.author.isEmpty()) {
        painter.save();
        painter.setFont(m_settings.coverPage.authorFont);
        painter.setPen(Qt::black);
        QPoint authorPos = contentArea.center() + m_authorOffset;
        QFontMetrics fm(m_settings.coverPage.authorFont);
        QString author = m_settings.coverPage.author;
        int maxWidth = contentArea.width() - qAbs(m_authorOffset.x()) * 2;
        maxWidth = qMax(maxWidth, static_cast<int>(50 * mmToPixels));
        QStringList lines;
        if (fm.horizontalAdvance(author) <= maxWidth) {
            lines << author;
        } else {
            QStringList words = author.split(' ');
            QString currentLine;
            for (const QString& word : words) {
                QString testLine = currentLine.isEmpty() ? word : currentLine + " " + word;
                if (fm.horizontalAdvance(testLine) <= maxWidth) {
                    currentLine = testLine;
                } else {
                    if (!currentLine.isEmpty()) {
                        lines << currentLine;
                        currentLine = word;
                    } else {
                        lines << word;
                    }
                }
            }
            if (!currentLine.isEmpty()) {
                lines << currentLine;
            }
        }
        int lineHeight = fm.lineSpacing();
        int totalHeight = lines.size() * lineHeight;
        int startY = authorPos.y() - totalHeight / 2;
        for (int i = 0; i < lines.size(); ++i) {
            QRect lineRect(authorPos.x() - maxWidth/2, startY + i * lineHeight, 
                          maxWidth, lineHeight);
            painter.drawText(lineRect, Qt::AlignCenter, lines[i]);
        }
        painter.restore();
    }
    // 渲染日期（真实字体大小）
    if (!m_settings.coverPage.date.isEmpty()) {
        painter.save();
        painter.setFont(m_settings.coverPage.dateFont);
        painter.setPen(Qt::black);
        QPoint datePos = contentArea.center() + m_dateOffset;
        QFontMetrics fm(m_settings.coverPage.dateFont);
        QString date = m_settings.coverPage.date;
        int maxWidth = contentArea.width() - qAbs(m_dateOffset.x()) * 2;
        maxWidth = qMax(maxWidth, static_cast<int>(50 * mmToPixels));
        QStringList lines;
        if (fm.horizontalAdvance(date) <= maxWidth) {
            lines << date;
        } else {
            QStringList words = date.split(' ');
            QString currentLine;
            for (const QString& word : words) {
                QString testLine = currentLine.isEmpty() ? word : currentLine + " " + word;
                if (fm.horizontalAdvance(testLine) <= maxWidth) {
                    currentLine = testLine;
                } else {
                    if (!currentLine.isEmpty()) {
                        lines << currentLine;
                        currentLine = word;
                    } else {
                        lines << word;
                    }
                }
            }
            if (!currentLine.isEmpty()) {
                lines << currentLine;
            }
        }
        int lineHeight = fm.lineSpacing();
        int totalHeight = lines.size() * lineHeight;
        int startY = datePos.y() - totalHeight / 2;
        for (int i = 0; i < lines.size(); ++i) {
            QRect lineRect(datePos.x() - maxWidth/2, startY + i * lineHeight, 
                          maxWidth, lineHeight);
            painter.drawText(lineRect, Qt::AlignCenter, lines[i]);
        }
        painter.restore();
    }
}
void PreviewPageWidget::renderContentPageToCanvas(QPainter& painter, const QRect& canvasRect) const
{
    // 计算内容区域（考虑边距）
    const double dpi = 300.0;
    const double mmToInch = 25.4;
    const double mmToPixels = dpi / mmToInch;
    int leftMargin = static_cast<int>(m_settings.margins.left * mmToPixels);
    int rightMargin = static_cast<int>(m_settings.margins.right * mmToPixels);
    int topMargin = static_cast<int>(m_settings.margins.top * mmToPixels);
    int bottomMargin = static_cast<int>(m_settings.margins.bottom * mmToPixels);
    QRect contentRect = canvasRect.adjusted(leftMargin, topMargin, -rightMargin, -bottomMargin);
    // 优先显示当前文件的第一页
    if (!m_currentFileFirstPage.isNull()) {
        // 缩放当前文件第一页以适应内容区域
        QImage scaledImage = m_currentFileFirstPage.scaled(contentRect.size(), 
                                                           Qt::KeepAspectRatio, 
                                                           Qt::SmoothTransformation);
        // 居中绘制图片
        QPoint imagePos = contentRect.center() - QPoint(scaledImage.width()/2, scaledImage.height()/2);
        painter.drawImage(imagePos, scaledImage);
    } else if (!m_sampleImage.isNull()) {
        // 如果没有当前文件第一页，使用示例图片
        QImage scaledImage = m_sampleImage.scaled(contentRect.size(), 
                                                 Qt::KeepAspectRatio, 
                                                 Qt::SmoothTransformation);
        // 居中绘制图片
        QPoint imagePos = contentRect.center() - QPoint(scaledImage.width()/2, scaledImage.height()/2);
        painter.drawImage(imagePos, scaledImage);
    } else {
        // 如果都没有，显示灰色占位符
        painter.fillRect(contentRect, QColor(240, 240, 240));
        painter.setPen(Qt::gray);
        QFont font("Arial", 12);
        painter.setFont(font);
        painter.drawText(contentRect, Qt::AlignCenter, tr("无内容预览"));
    }
}
void PreviewPageWidget::renderHeaderFooterToCanvas(QPainter& painter, const QRect& canvasRect) const
{
    const double dpi = 300.0;
    const double mmToInch = 25.4;
    const double mmToPixels = dpi / mmToInch;
    // 渲染页眉（真实渲染效果）
    if (m_settings.header.enabled) {
        painter.save();
        painter.setFont(m_settings.header.font);
        painter.setPen(m_settings.header.color);
        // 计算页眉区域，考虑边距
        int headerTop = static_cast<int>(5 * mmToPixels); // 页眉距离顶部5mm
        int headerHeight = static_cast<int>(10 * mmToPixels); // 页眉高度10mm
        int headerLeft = static_cast<int>(m_settings.margins.left * mmToPixels);
        int headerWidth = canvasRect.width() - static_cast<int>((m_settings.margins.left + m_settings.margins.right) * mmToPixels);
        QRect headerRect(headerLeft, headerTop, headerWidth, headerHeight);
        // 计算对齐方式
        Qt::Alignment headerAlign = Qt::AlignVCenter;
        switch (m_settings.header.position) {
            case HeaderFooterPosition::Left:
                headerAlign |= Qt::AlignLeft;
                break;
            case HeaderFooterPosition::Center:
                headerAlign |= Qt::AlignHCenter;
                break;
            case HeaderFooterPosition::Right:
                headerAlign |= Qt::AlignRight;
                break;
        }
        // 替换变量，实现真实的变量替换
        QString headerText = m_settings.header.text;
        headerText.replace("{title}", m_settings.coverPage.title);
        headerText.replace("{date}", m_settings.coverPage.date);
        headerText.replace("{page}", "1");
        headerText.replace("{totalPages}", "10");
        // 支持多行页眉，使用真实的字体渲染
        QFontMetrics fm(m_settings.header.font);
        QStringList lines = headerText.split('\n');
        int lineHeight = fm.lineSpacing();
        int totalHeight = lines.size() * lineHeight;
        int startY = headerRect.top() + (headerRect.height() - totalHeight) / 2;
        for (int i = 0; i < lines.size(); ++i) {
            QRect lineRect(headerRect.left(), startY + i * lineHeight, 
                          headerRect.width(), lineHeight);
            painter.drawText(lineRect, headerAlign, lines[i]);
        }
        painter.restore();
    }
    // 渲染页脚（真实渲染效果）
    if (m_settings.footer.enabled) {
        painter.save();
        painter.setFont(m_settings.footer.font);
        painter.setPen(m_settings.footer.color);
        // 计算页脚区域，考虑边距
        int footerBottom = canvasRect.height() - static_cast<int>(5 * mmToPixels); // 页脚距离底部5mm
        int footerHeight = static_cast<int>(10 * mmToPixels); // 页脚高度10mm
        int footerLeft = static_cast<int>(m_settings.margins.left * mmToPixels);
        int footerWidth = canvasRect.width() - static_cast<int>((m_settings.margins.left + m_settings.margins.right) * mmToPixels);
        QRect footerRect(footerLeft, footerBottom - footerHeight, footerWidth, footerHeight);
        // 计算对齐方式
        Qt::Alignment footerAlign = Qt::AlignVCenter;
        switch (m_settings.footer.position) {
            case HeaderFooterPosition::Left:
                footerAlign |= Qt::AlignLeft;
                break;
            case HeaderFooterPosition::Center:
                footerAlign |= Qt::AlignHCenter;
                break;
            case HeaderFooterPosition::Right:
                footerAlign |= Qt::AlignRight;
                break;
        }
        // 替换变量，实现真实的变量替换
        QString footerText = m_settings.footer.text;
        footerText.replace("{title}", m_settings.coverPage.title);
        footerText.replace("{date}", m_settings.coverPage.date);
        footerText.replace("{page}", "1");
        footerText.replace("{totalPages}", "10");
        // 支持多行页脚，使用真实的字体渲染
        QFontMetrics fm(m_settings.footer.font);
        QStringList lines = footerText.split('\n');
        int lineHeight = fm.lineSpacing();
        int totalHeight = lines.size() * lineHeight;
        int startY = footerRect.top() + (footerRect.height() - totalHeight) / 2;
        for (int i = 0; i < lines.size(); ++i) {
            QRect lineRect(footerRect.left(), startY + i * lineHeight, 
                          footerRect.width(), lineHeight);
            painter.drawText(lineRect, footerAlign, lines[i]);
        }
        painter.restore();
    }
}
